package com.clippick;

import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import co.kr.clippick.R;

import com.clippick.common.GlobalValue;
import com.clippick.history.HistoryFragment;
import com.clippick.setting.SettingFragment;

public class TabFragment extends Fragment implements OnClickListener {

	// common
	private Context mContext;

	// state
	private static int HISTORY_STATE = 1;
	private static int STAR_STATE = 2;
	private static int SETTING_STATE = 3;

	// data:info
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;

	private int mTabState = -1;

	// view
	public ProgressBar indicator;
	private Button historyButton, starButton, settingButton;
	private LinearLayout pieLayer;
	private HistoryFragment historyFragment;

	// chart
	private static double maxValue = 0;
	private static double countValue = 0;

	// count: using
	private final static int color1 = 0xff9f9f9f;

	// remains for < 33%: max - count
	private final static int color2 = 0xff8fae00;

	// remains for < 67% : max - count
	private final static int color3 = 0xffe4a600;

	// remains for < 100% : max - count
	private final static int color4 = 0xffb60055;

	// 1% - 33%
	private final static int[] COLORS = new int[] { color2, color1 };

	// 34% - 67%
	private final static int[] COLORS_HALF_MAX = new int[] { color3, color1 };

	// 68% - 100%
	private final static int[] COLORS_ALMOST_MAX = new int[] { color4, color1 };

	private static CategorySeries mSeries = new CategorySeries("");
	private static DefaultRenderer mRenderer = new DefaultRenderer();
	private static GraphicalView mChartView;

	// start view
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = (Context) getActivity();
		View view = inflater.inflate(R.layout.fragment_tab, container, false);

		pref = mContext.getSharedPreferences(GlobalValue.KEY,
				Context.MODE_PRIVATE);
		editor = mContext.getSharedPreferences(GlobalValue.KEY,
				Context.MODE_PRIVATE).edit();

		historyFragment = new HistoryFragment();

		indicator = (ProgressBar) view.findViewById(R.id.indicator);
		// hide default
		indicator.setVisibility(View.INVISIBLE);

		historyButton = (Button) view.findViewById(R.id.history_button);
		starButton = (Button) view.findViewById(R.id.star_button);
		settingButton = (Button) view.findViewById(R.id.setting_button);
		pieLayer = (LinearLayout) view.findViewById(R.id.pie_layer);
		pieLayer.setBackgroundColor(Color.WHITE);
		pieLayer.setVisibility(View.GONE);

		historyButton.setOnClickListener(this);
		starButton.setOnClickListener(this);
		settingButton.setOnClickListener(this);

		/*
		 * IllegalArgumentException: 백그라운드에서 들어온 데이터의 star count 계산 후, 뷰 업데이트하다가
		 * 에러 발생.
		 */
		// this.setPieChart();

		if (!pref.getString("max", "").equals("")) {
			double count = Double.parseDouble(pref.getString("count", ""));
			double max = Double.parseDouble(pref.getString("max", ""));
			this.setValue(max, 0);
			this.setValue(count, 1);
		}

		return view;
	}

	public void updateFeed() {
		historyFragment.updateFeed();
	}

	/** history screen */
	public void historyFragment() {
		if (mTabState != HISTORY_STATE) {
			mTabState = HISTORY_STATE;
			// Log.i("fragment", "history");
			FragmentManager fm = getFragmentManager();
			if (fm != null) {
				historyButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_clip_a));
				starButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_star_h));
				settingButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_setting_n));

				FragmentTransaction ft = fm.beginTransaction();
				historyFragment = new HistoryFragment();
				ft.replace(R.id.fragment_content, historyFragment);
				ft.commit();
			}
		}
	}

	public void starFragment() {
		if (mTabState != STAR_STATE) {
			mTabState = STAR_STATE;
			// Log.i("fragment", "star");
			FragmentManager fm = getFragmentManager();
			Bundle bundle = new Bundle();
			bundle.putBoolean("star", true);
			if (fm != null) {
				historyButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_clip_s));
				starButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_star_a));
				settingButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_setting_n));

				FragmentTransaction ft = fm.beginTransaction();
				historyFragment = new HistoryFragment();
				historyFragment.setArguments(bundle);
				ft.replace(R.id.fragment_content, historyFragment);
				ft.commit();
			}
		}
	}

	public void settingFragment() {
		if (mTabState != SETTING_STATE) {
			mTabState = SETTING_STATE;
			// Log.i("fragment", "setting");
			FragmentManager fm = getFragmentManager();
			if (fm != null) {
				historyButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_clip_n));
				starButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_star_n));
				settingButton.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_setting_a));
				FragmentTransaction ft = fm.beginTransaction();
				ft.replace(R.id.fragment_content, new SettingFragment());
				ft.commit();
			}
		}
	}

	public void handleIndicator(boolean value) {
		if (value) {
			// show
			indicator.setVisibility(View.VISIBLE);
			GlobalValue.IS_UPDATING = true;
		} else {
			// hide
			indicator.setVisibility(View.INVISIBLE);
			GlobalValue.IS_UPDATING = false;
		}
	}

	// access from setting: animate icon to rotate
	public void rotateIcon(int id) {
		Animation animation = AnimationUtils.loadAnimation(mContext,
				R.anim.rotate_to_right);

		if (id == R.id.setting_button) {
			settingButton.setAnimation(animation);
			settingButton.startAnimation(animation);

		} else if (id == R.id.history_button) {
			historyButton.startAnimation(animation);

		} else if (id == R.id.star_button) {
			starButton.startAnimation(animation);
		}
	}

	public void setPieChart() {
		mChartView = null;
		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setBackgroundColor(0xfff1f1f1);
		mRenderer.setChartTitleTextSize(0);
		mRenderer.setLabelsTextSize(0);
		mRenderer.setLegendTextSize(0);
		mRenderer.setZoomButtonsVisible(false);
		mRenderer.setStartAngle(180);
		mRenderer.setShowLabels(false);
		mRenderer.setShowLegend(false);
		mRenderer.setShowCustomTextGrid(false);

		if (mChartView == null) {
			mChartView = ChartFactory.getPieChartView(mContext, mSeries,
					mRenderer);
			mRenderer.setClickEnabled(false);
			mRenderer.setSelectableBuffer(10);

			// 960x540 에서 파이차트 크기가 커서 갈라짐
			pieLayer.addView(mChartView, new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		} else {
			mChartView.repaint();
		}
	}

	public static void setValue(double val, int position) {
		double x = val;
		int n = mSeries.getItemCount();
		if (n != 0) {
			if ((n % 2) == 0) {
				mSeries.remove(position);
				mSeries.remove(position);
				// max value
				maxValue = val;
			} else {
				// count value
				countValue = val;
			}
		}

		mSeries.add("Series " + (mSeries.getItemCount() + 1), x);
		SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();

		// for default color
		renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);

		// set color for different percentage
		if (maxValue != 0 && countValue != 0) {
			double starPercent = (countValue / maxValue) * 100;
			// Log.i("star", "percent : " + starPercent);
			if (starPercent > 67.0) {
				renderer.setColor(COLORS_ALMOST_MAX[(mSeries.getItemCount() - 1)
						% COLORS_ALMOST_MAX.length]);
			} else if (starPercent < 33.0) {
				renderer.setColor(COLORS[(mSeries.getItemCount() - 1)
						% COLORS.length]);
			} else if (starPercent > 33.0 && starPercent < 67.0) {
				renderer.setColor(COLORS_HALF_MAX[(mSeries.getItemCount() - 1)
						% COLORS_HALF_MAX.length]);
			}
		}

		mRenderer.addSeriesRenderer(renderer);
		mRenderer.addSeriesRenderer(position, renderer);
		if (mChartView != null) {
			mChartView.repaint();
		}
	}

	public static void setValue() {
		Map<String, String> values = GlobalValue.MAP_STAR_DATA;
		double max = Double.parseDouble(values.get("max"));
		double count = Double.parseDouble(values.get("count"));
		setValue(max, 0);
		setValue(count, 1);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.history_button:
			this.historyFragment();
			break;

		case R.id.star_button:
			this.starFragment();
			break;

		case R.id.setting_button:
			this.settingFragment();
			break;
		}
	}
}
